//
//  IncomeCostListDetailViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/11/28.
//  Copyright © 2018 xyxorigation. All rights reserved.
//

import UIKit
import SnapKit
class IncomeCostListDetailViewController: PagedViewController {

    var planType: String = ""
    var planId: String = ""
    //将下面的属性写成计算属性
    var orderType = 1
    // 收入 升序 将序
    //成本 升序 将序
    //    1: 按收入完成率由低到高
    //    2: 按收入完成率由高到低
    //    3: 按成本完成率由低到高
    //    4: 按成本完成率由高到低
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(refresh(not:)), name: NSNotification.Name("RefreshDetail"), object: nil)
        self.load(with: "Detail")
        // Do any additional setup after loading the view.
    }
    
    @objc func refresh(not: Notification){
        if let obj = not.object as? Int {
            self.orderType = obj
            self.load(with: self.names[0])
        }
    }
    
    override var names: Array<String>{
        return ["Detail"]
    }
    override func path(for name: String) -> String {
        return ComprehensiveListDetail
    }
    
    override func param(for name: String) -> Dictionary<String, Any> {
        return ["planType":planType,"planId":planId,"orderType": self.orderType]
    }
    
    override func method(for name: String) -> NetMethod {
        return .get
    }
    
    
    override func success(for name: String) -> NetSuccess {
        func suc(json: JSON)->Void{
            if let success = json.contents?["success"]?.bool {
                
                if success == true {
                    if let data = json.contents?["data"]?.contents {
                        var contents: [Dictionary<String,String?>] = []
                        contents.append(["统计计划编号:": data["serialnumber"]?.rawString()])
                        contents.append(["综合计划名称:": data["compositeName"]?.rawString()])
                        contents.append(["归属部门:": data["belongdeptone"]?.rawString()])
                        contents.append(["计划属性:": data["typeplanName"]?.rawString()])
                        
                        let income = (data["income"]?.int ?? 0) / 100
                        contents.append(["收入(元):": String(income).rmbformat])
                        let cost = (data["cost"]?.int ?? 0) / 100
                        contents.append(["成本(元):":String(cost).rmbformat])
                        let ml = (income - cost) > 0 ? income - cost : 0
                        contents.append(["毛利(元):": String(ml / 100).rmbformat])
                        let mlrat = (Double(ml) / Double(cost)) * 100
                        let mlratstr = String(lround(mlrat)) + "%"
                        contents.append(["毛利率:": mlratstr])
                        let titlecontent = self.ctls[1] as! TitleContentTableViewController
                        titlecontent.source = contents
                        titlecontent.tableView.reloadData()
                        
                        let listProj = data["listProj"]?.array ?? []
                        let second = self.ctls[0] as! IncomeCostProjects
                        second.source = listProj
                        second.tableView.reloadData()
                    }
                } else {
                    self.alert(json.contents?["errorMsg"]?.rawString())
                }
                
            } else {
                self.alert(json.contents?["errorMsg"]?.rawString())
            }
        }
        return suc
    }
    
//    override func success(for name: String) -> NetSuccess {
//        func suc(json: JSON)->Void{
//            if let success = json.contents?["success"]?.bool {
//
//                if success == true {
//                    if let data = json.contents?["data"]?.contents {
//                        var contents: [Dictionary<String,String?>] = []
//                        contents.append(["统计计划编号:": data["planNumber"]?.rawString()])
//                        contents.append(["归属部门:": data["belongDeptOrgName"]?.rawString()])
//                        contents.append(["计划名称:": data["planName"]?.rawString()])
//
//                        var typename = ""
//                        let type = data["businessType"]?.int ?? 0
//                        switch type {
//                        case 1:
//                            typename =  "产品销售"
//                            break
//                        case 2:
//                            typename =  "商品销售";
//                            break
//                        case 3:
//                            typename = "技术服务";
//                            break
//                        case 4:
//                            typename = "勘测设计";
//                            break
//                        case 5:
//                            typename = "工程安装";
//                            break
//                        case 6:
//                            typename = "节能服务"
//                            break
//                        case 7:
//                            typename = "后勤物业"
//                            break
//                        case 8:
//                            typename = "监理业务"
//                            break
//                        case 9:
//                            typename = "其他业务"
//                            break
//                        case 10:
//                            typename = "增量业务"
//                            break
//                        case 11:
//                            typename =  "工程"
//                            break
//                        case 12:
//                            typename = "经营性租赁"
//                            break
//                        default:
//                            typename = "未知"
//                        }
//                        contents.append(["业务类型:": typename])
//                        let income = (data["income"]?.int ?? 0) / 100
//                        contents.append(["收入(元):": String(income).rmbformat])
//                        let cost = (data["cost"]?.int ?? 0) / 100
//                        contents.append(["成本(元):":String(cost).rmbformat])
//                        let ml = (income - cost) > 0 ? income - cost : 0
//                        contents.append(["毛利(元):": String(ml / 100).rmbformat])
//                        let mlrat = (Double(ml) / Double(cost)) * 100
//                        let mlratstr = String(lround(mlrat)) + "%"
//                        contents.append(["毛利率:": mlratstr])
//                        contents.append(["专业管理部门:": "市场营销部"])
//                        let titlecontent = self.ctls[0] as! TitleContentTableViewController
//                        titlecontent.source = contents
//                        titlecontent.tableView.reloadData()
//                        let listProj = data["listProj"]?.array ?? []
//                        let second = self.ctls[1] as! IncomeCostProjects
//                        second.source = listProj
//                        print(second.source)
//                        second.tableView.reloadData()
//                    }
//
//
//
//                } else {
//                    self.alert(json.contents?["errorMsg"]?.rawString())
//                }
//            } else {
//                self.alert(json.contents?["errorMsg"]?.rawString())
//            }
//        }
//        return suc
//    }
    
    override func configTitles() -> Array<String> {
        return ["关联项目","基本信息"]
    }
    
    override func configViewControllers() -> [UIViewController] {
        return [IncomeCostProjects(),TitleContentTableViewController()]
    }

}

import SnapKit
class IncomeCostProjects: BaseTableViewController,UIPickerViewDelegate,UIPickerViewDataSource {
    
    var planType = ""
    var planId = ""
    
    var source: [JSON] = []
    
    enum WhitchSelect {
        case Left
        case Right
        case None
    }
    
    var whitch: WhitchSelect = .None
    let field = UITextField()
    func popleftselect()->Void{
        self.whitch = .Left
        self.field.becomeFirstResponder()
    }
    func poprightselect()->Void{
        self.whitch = .Right
        self.field.becomeFirstResponder()
    }
    
    override func endedit() {
        super.endedit()
        switch self.whitch {
        case .Left:
            if picker.selectedRow(inComponent: 0) == 0 {
                //收入完成率升序
                NotificationCenter.default.post(name: Notification.Name("RefreshDetail"), object: 1)
                selectview.incomecompleterate = .Ascending
                self.selectview.badgecompleterate = .UnKnown
            } else {
                //收入完成率将序
                NotificationCenter.default.post(name: Notification.Name("RefreshDetail"), object: 2)
                selectview.incomecompleterate = .DeAscending
//                self.selectview.incomecompleterate = .Ascending
                self.selectview.badgecompleterate = .UnKnown
            }
            break
        default:
            if picker.selectedRow(inComponent: 0) == 0 {
                //成本完成率升序
                NotificationCenter.default.post(name: Notification.Name("RefreshDetail"), object: 3)
                selectview.badgecompleterate = .Ascending
                self.selectview.incomecompleterate = .UnKnown
            } else {
                //陈本完成率将序
                NotificationCenter.default.post(name: Notification.Name("RefreshDetail"), object: 4)
                selectview.badgecompleterate = .DeAscending
                self.selectview.incomecompleterate = .UnKnown
            }
            break
        }
    }
    
    let picker = UIPickerView.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize(width: UIScreen.main.bounds.size.width, height: 220)))
    
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 2
    }
    
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 35
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let Label = UILabel()
        Label.font = UIFont.systemFont(ofSize: 14)
        Label.textAlignment = .center
        switch row {
        case 0:
            Label.text = "升序"
        default:
            Label.text = "降序"
        }
        return Label
    }
    
    let selectview = Bundle.main.loadNibNamed("SortView", owner: nil, options: nil)![0] as! SortView
    override func viewDidLoad() {
        super.viewDidLoad()
        self.selectview.incomecompleterate = .Ascending
        self.selectview.badgecompleterate = .UnKnown
        picker.backgroundColor = UIColor.white
        picker.delegate = self
        picker.dataSource = self
        self.view.addSubview(field)
        field.inputView = picker
        self.tableView.separatorInset = .zero
        field.inputAccessoryView = self.toolbarview
        self.tableView.showsVerticalScrollIndicator = false
        self.tableView.register(UINib.init(nibName: "AssociateProjsCell", bundle: Bundle.main), forCellReuseIdentifier: "AssociateProjsCell")
        
        self.load(with: "Detail")
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 54
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .dftBack
        let line = UIView()
        line.frame = CGRect.init(origin: CGPoint.zero, size: CGSize(width: self.view.width, height: 10))
        line.backgroundColor = UIColor.dftBack
        view.addSubview(line)
        selectview.delegate = self
        view.addSubview(selectview)
        selectview.snp.makeConstraints({ (make) in
            make.top.equalTo(10)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(44)
        })
        let linebottom = UIView()
        view.addSubview(linebottom)
        linebottom.backgroundColor = UIColor.tableSeparator
        linebottom.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalTo(0.5)
            make.bottom.equalToSuperview()
            make.left.equalToSuperview()
        }
        return view
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCell(withIdentifier: "AssociateProjsCell")!
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = self.source[indexPath.row]
        let string = model.contents?["gsProjName"]?.rawString() ?? ""
        let size = "我".size(with: UIFont.boldSystemFont(ofSize: 18))
        let size1 = string.size(with: UIFont.boldSystemFont(ofSize: 18), maxSize: CGSize(width: self.view.width - 40, height: 1000000))
        return 145 + size1.height - size.height
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return source.count
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if let cel = cell as? AssociateProjsCell {
            cel.model = self.source[indexPath.row]
        }
    }
    
}
